package com.jingyanzi.member.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jingyanzi.member.dao.MSaleContactRecordMapper;
import com.jingyanzi.member.domain.CustomerFamilyDO;
import com.jingyanzi.member.domain.SaleContactRecordDO;
import com.jingyanzi.member.domain.result.ResultDO;
import com.jingyanzi.member.domain.result.ResultSupport;
import com.jingyanzi.member.entity.MSaleContactRecord;
import com.jingyanzi.member.entity.MSaleContactRecordExample;
import com.jingyanzi.member.entity.MSaleContactRecordExample.Criteria;
import com.jingyanzi.member.query.SaleContactRecordQueryDO;
import com.jingyanzi.member.service.IAnalysisService;
import com.jingyanzi.member.service.ICustomerFamilyService;
import com.jingyanzi.member.service.ISalesRecordService;
import com.jingyanzi.member.util.BeanUtilsExtends;
import com.jingyanzi.member.util.MemberConstant;

@Service("salesRecordService")
public class SalesRecordServiceImpl extends BaseServiceImpl implements ISalesRecordService {

	private static Logger logger = Logger.getLogger(SalesRecordServiceImpl.class);

	@Autowired
	private MSaleContactRecordMapper saleContactRecordMapper;
	@Autowired
	private ICustomerFamilyService customerFamilyService;
	@Autowired
	private IAnalysisService analysisService;

	@Override
	public ResultDO add(SaleContactRecordDO domain) {

		MSaleContactRecord entity = new MSaleContactRecord();

		ResultSupport result = BeanUtilsExtends.copy(entity, domain);
		if (!result.isSuccess()) {
			result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("客户销售活动记录处理失败");
			result.setSuccess(false);
			logger.error("客户销售活动记录DO对象转换失败");
			return result;
		}

		if (StringUtils.isNotEmpty(domain.getNextDateStamp())) {
			entity.setNextDate(new Date(Long.parseLong(domain.getNextDateStamp())));
		}
		// 获取联系人
		if (StringUtils.isEmpty(domain.getContact()) && !isNumberInValid(domain.getContactId())) {
			ResultDO resultDO = customerFamilyService.get(domain.getContactId());
			if (resultDO.isSuccess()) {
				CustomerFamilyDO familyDO = (CustomerFamilyDO) resultDO.getModel(ResultDO.FIRST_MODEL_KEY);
				entity.setContact(familyDO.getName());
			}
		}
		entity.setIsDelete(MemberConstant.DB_ISDEL_NO);
		entity.setCreateTime(Calendar.getInstance().getTime());
		entity.setEditable(0);

		int r = -1;
		try {
			r = saleContactRecordMapper.insert(entity);
		} catch (Exception e) {
			e.printStackTrace();
			result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("客户销售活动记录添加失败");
			result.setSuccess(false);

			return result;
		}
		if (r < 1) {
			result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("客户销售活动记录添加失败");
			result.setSuccess(false);

			return result;
		}

		// 如果是线索， 判断是否需要更新线索状态
		if (!isNumberInValid(domain.getLeadId())) {
			Date followTime = (domain.getIsAddAuto() == 1) ? null : Calendar.getInstance().getTime();
			analysisService.updateFollow(domain.getId(), domain.getStatus(), followTime, entity.getNextDate());
		}

		result.setModel(ResultDO.FIRST_MODEL_KEY, entity.getId());
		return result;
	}

	public ResultDO query(SaleContactRecordQueryDO query) {

		ResultSupport result = new ResultSupport();

		MSaleContactRecordExample example = new MSaleContactRecordExample();

		Criteria createCriteria = example.createCriteria();
		if (!isNumberInValid(query.getLeadId())) {
			createCriteria.andLeadIdEqualTo(query.getLeadId());
		}
		if (!isNumberInValid(query.getCustomerId())) {
			createCriteria.andCustomerIdIn(createCustomerId(query.getCustomerId()));
		}
		createCriteria.andIsDeleteEqualTo(MemberConstant.DB_ISDEL_NO);

		if (query.isPage()) {
			example.setLimitByPage(query.getStart() + "," + query.getPageRows());
			long count = saleContactRecordMapper.countByExample(example);
			result.setModel(ResultSupport.SECOND_MODEL_KEY, count);
		}

		List<MSaleContactRecord> list = null;
		try {
			list = saleContactRecordMapper.selectByExample(example);
		} catch (Exception e) {
			e.printStackTrace();
			result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("客户销售活动记录信息查询失败");
			result.setSuccess(false);
			logger.error("客户销售活动记录信息查询失败");
			return result;
		}

		List<SaleContactRecordDO> listDO = getSalesRecordDOList(list);
		result.setModel(ResultSupport.FIRST_MODEL_KEY, listDO);

		return result;
	}

	@Override
	public ResultDO getLatestRecord(SaleContactRecordQueryDO query) {

		ResultSupport result = new ResultSupport();
		MSaleContactRecordExample example = new MSaleContactRecordExample();

		Criteria createCriteria = example.createCriteria();
		if (!isNumberInValid(query.getLeadId())) {
			createCriteria.andLeadIdEqualTo(query.getLeadId());
		}
		if (!isNumberInValid(query.getCustomerId())) {
			createCriteria.andCustomerIdIn(createCustomerId(query.getCustomerId()));
		}
		createCriteria.andIsDeleteEqualTo(MemberConstant.DB_ISDEL_NO);
		example.setOrderByClause("createTime desc ");
		example.setLimitByPage("0,1");

		List<MSaleContactRecord> list = null;
		try {
			list = saleContactRecordMapper.selectByExample(example);
		} catch (Exception e) {
			e.printStackTrace();
			result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("客户销售活动记录信息查询失败");
			result.setSuccess(false);
			logger.error("客户销售活动记录信息查询失败");
			return result;
		}

		if (list == null || list.size() < 1) {
			result.setSuccess(false);
			result.setErrorMsg("暂无记录");
			return result;
		}
		result.setModel(ResultSupport.FIRST_MODEL_KEY, getSalesRecordDO(list.get(0)));

		return result;
	}

	/**
	 * 对象拷贝单个实体到对象中
	 * 
	 * @param obj
	 * @return 返回DO对象
	 */
	public SaleContactRecordDO getSalesRecordDO(MSaleContactRecord entity) {
		SaleContactRecordDO dst = new SaleContactRecordDO();
		if (entity == null)
			return dst;
		dst.setCreateTimeName(entity.getCreateTime().getTime() + "");
		if (null != entity.getNextDate()) {
			dst.setNextDateStamp(entity.getNextDate().getTime() + "");
		}
		return BeanUtilsExtends.copyProperties(dst, entity) ? dst : null;
	}

	/**
	 * 对象拷贝多个实体到列表中
	 * 
	 * @param List
	 * @return List
	 */
	public List<SaleContactRecordDO> getSalesRecordDOList(List<MSaleContactRecord> list) {
		List<SaleContactRecordDO> result = new ArrayList<SaleContactRecordDO>();
		if (list != null && !list.isEmpty()) {
			for (MSaleContactRecord entity : list) {
				SaleContactRecordDO domain = getSalesRecordDO(entity);
				if (domain != null) {
					result.add(domain);
				}
			}
		}
		return result;
	}

}
